package main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main extends Thread {
   
	public static Main main;
   public static final int STARTING_PORT = 4444;
   public static List<Room> rooms;
   public static Room mainRoom;
   private ServerSocket serverSocket;
   private Socket userSocket;
   
   public static Room testRoom;

   public static void main(String[] args) {
      try {
      	main = new Main();
      } catch (IOException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
      }
   }
   
   @Override
   public void run() {
   	try {
	      listenConnections();
      } catch (IOException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
      }
   }

	public Main() throws IOException {
		serverSocket = new ServerSocket(4444);
      rooms = new ArrayList<Room>();
      addRoom(mainRoom = new Room("Main Lobby"));
      addRoom(testRoom = new Room("Test Room"));
      start();
   }
   
   private void listenConnections() throws IOException {
   	while(true) {
   		userSocket = serverSocket.accept();
         User u = new User(userSocket, mainRoom);
         mainRoom.addUser(u);
         u.start();
   	}
   }
   
   public void addRoom(Room room) {
   	rooms.add(room);
   }
   
   public Room getRoomByName(String name) {
   	for (Room room : rooms) {
   		if (room.getName().equals(name)) {
   			return room;
   		}
   	}
   	return null;
   }
   
   /**
    * Dispatches a global server message for everyone to see
    */
   public void dispatchServerMsg(String msg) {
      for (Room room : rooms) {
         for (User user : room.users) {
            user.dispatch(Messages.SERVER + " " + msg);
         }
      }
   }

}
